package com.example.securitydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.securitydemo.entity.AclUser;
import com.example.securitydemo.mapper.AclUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AclUserMapper aclUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("student");
        QueryWrapper<AclUser> wrapper = new QueryWrapper<AclUser>()
                .eq("username",userName);
        AclUser aclUser = aclUserMapper.selectOne(wrapper);
        if (aclUser==null){
            throw new UsernameNotFoundException("用户不存在！");
        }

        UserDetails user = new User(aclUser.getUserName(),new BCryptPasswordEncoder().encode(aclUser.getPassword()),auths);
        return user;
    }
}
